var staticParam,queryParam;
$(function(){
    $.fn.raty.defaults.path = '/by-webhtml/assets/image';
    $('.halfShow-true-demo').raty({readOnly: false, score: 5 });
    laydate.skin('yahui');//切换皮肤，请查看skins下面皮肤库
    //日期范围限制
    var start = {
        elem: '#start',
        format: 'YYYY-MM-DD',
        // min: laydate.now(), //设定最小日期为当前日期
        max: '2099-06-16', //最大日期
        istime: true,
        istoday: false,
        choose: function(datas){
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };

    var end = {
        elem: '#end',
        format: 'YYYY-MM-DD',
        // min: laydate.now(),
        max: '2099-06-16',
        event: 'click',
        istime: true,
        istoday: false,
        choose: function(datas){
            start.max = datas; //结束日选好后，充值开始日的最大日期
        }
    };
    queryParam = null;
    staticParam = null;
    laydate(start);
    laydate(end);
    $('#start').val(laydate.now(-7, 'YYYY-MM-DD'));
    $('#end').val(laydate.now(0, 'YYYY-MM-DD'));
    getListPage({"curPage":1});
});


function queryPageList() {
    queryParam = null;
    staticParam = null;
    var obj = $(".controlDiv").serializeSearchForm();
    queryParam = $.extend(queryParam,obj);
    goPage(1);
    // getListPage($.extend(staticParam,{"curPage" : 1}));
}
function getListPageByStatus(status,obj,flag) {
    staticParam = null;
    queryParam = null;
    $(".orderTit a").removeClass();
    $(obj).addClass("cur");
    $("#myOrderPageHead ~ tr").remove();
    var param = $.extend({"status" : status},{"curPage" : 1});
    if(flag == 'evaluation'){
        param = $.extend({"userStars":-1},{"curPage" : 1});
    }else if(flag == 'payStatus'){
        param = $.extend({"payStatus":-1},{"curPage" : 1});
    }
    if(status == '1' || status == '2' || status == '20' || status == '6' || flag == 'evaluation'){
        param = $.extend(param,{"payStatus" : -2});
    }
    if(status == '' && flag != 'evaluation'){
        param = {"curPage" : 1};
    }
    staticParam = param;
    getListPage(param);
}

function getListPage(param){
    param = $.extend(queryParam,staticParam,param);
    $.ajax({
        type : "post",
        url : "htmlWeb/orderManagerList",
        data: $.extend({"userFlag" : 3},param),
        async: false,
        success : function(data){
            $("#myOrderPageHead ~ tr").remove();
            var str = "";
            $.each(data.rows,function(i,obj){
                obj = trimEmpty(obj);
                var createTime = formatDate(obj.createTime,"yyyy-MM-dd HH:mm:ss");
                var payType = renderPayType(obj.payType);
                var status = renderOrderStatus(obj.status);
                var payStatus = renderOrderPayStatus(obj.payStatus);
                var mobile = obj.user.mobile1 == 'admin' ? "" : obj.user.mobile1;
                str += '<tr><td><label><input type="checkbox" name="subBox" value="' + obj.id + '" class="selectDiv" /></label></td>' +
                    '<td><p>' + obj.id + '</p></td>' +
                    '<td><p>' + obj.user.cnName + '</p></td>' +
                    '<td><p>' + mobile + '</p></td>' +
                    '<td><p>' + payType + '</p></td>' +
                    '<td><p>' + obj.price + '</p></td>' +
                    '<td><p>' + obj.deposit + '</p></td>' +
                    '<td><p>' + status + '</p></td>' +
                    '<td><p>' + payStatus + '</p></td>' +
                    '<td><p>' + createTime + '</p></td>' +
                    '<td><span>' + obj.descn + '</span></td>' +
                    '<td><span class="userSpan">' +
                    '<a href="javascript:void(0);" onclick="showOrderInfo(' + obj.id + ')">订单详情</a>' ;


                if(obj.status == 1){
                    str += '<a href="javascript:void(0);" class="noteDiv" onclick="openPopupNote(' + obj.id + ')">添加备注</a>' ;
                }
                if(obj.payStatus != 1 && obj.payStatus != 2 && obj.status != 3){
                    str += '<a href="javascript:void(0);" onclick="payPrice(' + obj.id + ')">支付全款</a>' +
                           '<a href="javascript:void(0);" onclick="payDeposit(' + obj.id + ')">支付定金</a>';
                }else if((obj.payStatus == 1 || obj.payStatus == 2) && (obj.status != 6)){//付款后才能退款
                    str += '<a href="javascript:void(0);" class="refund" onclick="openPopupRefund(' + obj.id + ')">申请退款</a>';
                }
                if(obj.status == 5){
                    str += '<a href="javascript:void(0);" onclick="confirmOrder(' + obj.id + ')">订单完成</a>';
                }else if(obj.status == 6 && obj.userStars == ""){
                    str += '<a href="javascript:void(0);" class="evaluaDiv" onclick="openPopupEvaluate(' + obj.id + ')">填写评价</a>';
                }
                if(obj.payStatus == -1 && obj.status == 1){//未付款才能取消订单
                    str += '<a href="javascript:void(0);" class="callOrder" onclick="openPopupCancel(' + obj.id + ')">取消订单</a>';
                }
                str += '</span></td></tr>';
            });

            $("#myOrderPageHead").after(str);
            createPage(data);
            addCheckEvent();
        },
        error : function(data){
            console.log(data);
        }
    });
}

//组装选择id
function sumIds(){
    var orderIds = ""
    $("td :checkbox[name='subBox']").each(function(i,obj){
        if(obj.checked){
            orderIds += obj.value + ",";
        }
    });
    return orderIds;
}

//添加复选框点击事件
function addCheckEvent(){
    //全选
    $("#checkAll").click(function(){
        if(this.checked){
            $("th label").addClass("on");
            $("td label").addClass("on");
            $("td :checkbox[name='subBox']").prop("checked", true);
            $(".stores em").text($('.selectDiv').length);
        }else{
            $("th label").removeClass("on");
            $("td label").removeClass("on");
            $("td :checkbox[name='subBox']").prop("checked", false);
            $(".stores em").text(0);
        }

    });
    //单选
    $(".selectDiv").click(function(){
        if(this.checked){
            $(this).parent().addClass("on");
        }else{
            $(this).parent().removeClass("on");
        }
        if ($('.selectDiv').length == $('.selectDiv:checked').length) {
            $('#checkAll').prop({
                checked : true
            });
            $("th label").addClass("on");

        } else {
            $('#checkAll').prop({
                checked : false
            });
            $("th label").removeClass("on");

        }
    });
}

/**
 * 完成订单
 */
function confirmOrder(id){
    $.post("htmlWeb/updateOrderStatus",{"order_id":id,"status":6},function(data, textStatus, jqXHR){
        navPills("systemMineOrderHtml",2);
    });
}

/**
 * 查看详情
 * @param id
 */
function showOrderInfo(id){
    $(".mainDiv").load("systemOrderDetailsHtml",'',function(){
        $("#orderId").val(id);
        $("#parentFlag").val("mine");
        $.getScript("../../by-webhtml/assets/js/system/system_orderDetails.js");
    });
}
var orderId;

//退款弹出框
function openPopupRefund(id) {
    orderId = id;
    $(".deskDiv").css({
        display:"block",height:$(document).height()
    });
    $(".refundDiv").css({
        top:($(window).height()-$(".refundDiv").height())/2+$(window).scrollTop()+"px",
        display:"block"
    });
}

//退款
function refundOrder() {
    var desc = $("#refundContent").val();
    closePopup();

    $.post("htmlWeb/submitRefund",{"order_id":orderId,"descn":desc},function(data, textStatus, jqXHR){
        navPills("systemMineOrderHtml",2);
    });
}
//打开备注弹出框
function openPopupNote(id) {
    orderId = id;
    $(".deskDiv").css({
        display:"block",height:$(document).height()
    });
    $(".addNote").css({
        top:($(window).height()-$(".addNote").height())/2+$(window).scrollTop()+"px",
        display:"block"
    });
}

//添加备注
function addNoteOrder(){
    var desc = $("#noteContent").val();
    closePopup();

    $.post("htmlWeb/submitDescn",{"order_id":orderId,"descn":desc},function(data, textStatus, jqXHR){
        navPills("systemMineOrderHtml",2);
    });
}
//打开评论弹出框
function openPopupEvaluate(id){
    orderId = id;
    $(".deskDiv").css({
        display:"block",height:$(document).height()
    });
    $(".evaluation").css({
        top:($(window).height()-$(".evaluation").height())/2+$(window).scrollTop()+"px",
        display:"block"
    });
}

//评论
function evaluationOrder(){
    // $("#order_id").val(orderId);
    // var options = {
    //     url: '/htmlWeb/submitOrderComment',
    //     type: 'post',
    //     success: function (data) {
    //         closePopup();
    //         $.ajaxSetup({cache: false});
    //         navPills("systemMineOrderHtml",2);
    //     },
    //     error:function () {
    //         closePopup();
    //         $.ajaxSetup({cache: false});
    //         tip("上传失败");
    //         navPills("systemMineOrderHtml",2);
    //     }
    // };
    // $("#form").ajaxSubmit(options);
    //
    // return false;
    var desc = $("#evaluationDesc").val();
    var starNum = $("input[name='score']").val();
    $("#starNum").html(starNum + "分");
    closePopup();

    $.post("htmlWeb/submitOrderComment",{"order_id":orderId,"user_stars":starNum,"descn":desc},function(data, textStatus, jqXHR){
        navPills("systemMineOrderHtml",2);
    });
}
//打开取消弹出框
function openPopupCancel(id){
    orderId = id;
    $(".deskDiv").css({
        display:"block",height:$(document).height()
    });
    $(".cancleOrder").css({
        top:($(window).height()-$(".cancleOrder").height())/2+$(window).scrollTop()+"px",
        display:"block"
    });
}
//取消订单
function cancelOrder(){
    closePopup();
    $.post("htmlWeb/updateOrderStatus",{"order_id":orderId,"status":3},function(data, textStatus, jqXHR){
        navPills("systemMineOrderHtml",2);
    });
}
//关闭弹出框
function closePopup(){
    $(".deskDiv").fadeOut();
    $(".cancleOrder").fadeOut();
    $(".evaluation").fadeOut();
    $(".addNote").fadeOut();
    $(".refundDiv").fadeOut();
}

//支付全款
function payPrice(ids){
    if(ids == 'batch'){
        ids = sumIds();
    }
    if(ids == ""){
        tip('请选择要支付的订单');
        return;
    }
    window.open("htmlWeb/orderPay?order_id=" + ids + "&status=2");
    setTimeout(function(){
        navPills("systemMineOrderHtml",2);
    },500);
}
//支付定金
function payDeposit(ids){
    if(ids == 'batch'){
        ids = sumIds();
    }
    if(ids == ""){
        tip('请选择要支付的订单');
        return;
    }
    window.open("htmlWeb/orderPay?order_id=" + ids + "&status=1");
    setTimeout(function(){
        navPills("systemMineOrderHtml",2);
    },500);

}